<template>
  <div class="comment-tree">
    <!-- 递归渲染评论树 -->
    <div v-for="comment in comments" :key="comment.id" class="comment-item">
      <!-- 评论内容 -->
      <div class="comment-content">
        <el-avatar :size="40" :src="comment.entity.headIcon" />
        <div class="comment-info">
          <span class="comment-author">{{ comment.entity.nickname }}</span>
          <span v-html="comment.entity.comment" class="comment-text"></span>
        </div>
        <el-button size="small" @click="toggleReply(comment)">回复</el-button>
      </div>

      <!-- 回复输入框 -->
      <div v-if="comment.showReply" class="reply-input">
        <PageC v-model:valueHtml="listData" class="value-html"/>
        <el-button type="primary" size="small" @click="submitReply(comment,listData)">提交</el-button>
      </div>

      <!-- 递归渲染子评论 -->
      <div v-if="comment.children && comment.children.length > 0" class="child-comments">
        <CommentTree :comments="comment.children" />
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';
import { ElAvatar, ElButton, ElInput } from 'element-plus';
import PageC from '@/components/chat/TalkCreateNew.vue';
import talkAPI from "@/api/module/talk";

export default {
  name: 'CommentTree',
  components: {
    PageC,
    ElAvatar,
    ElButton,
    ElInput,
  },
  props: {
    comments: {
      type: Array,
      required: true,
    }
  },
  data() {
    return {
      listData: ''
    }
  },
  setup() {
    const replyText = ref(''); // 回复内容

    // 切换回复输入框的显示
    const toggleReply = (comment) => {
      comment.showReply = !comment.showReply;
    };

    // 提交回复
    const submitReply = async (comment,listData) => {
      const formData = new FormData();
      formData.append('parentId', comment.entity.id);
      formData.append('talkId', comment.entity.talkId);
      formData.append('comment', listData);
      await talkAPI.addComment(formData).then((res) => {
        comment.showReply = false;
        window.location.reload();
      }).catch((err) => {
        console.log(err)
      });
    };

    return {
      replyText,
      toggleReply,
      submitReply,
    };
  },
};
</script>

<style scoped>
.comment-tree {
  width: 100%;
  max-width: 700px;
  margin: 0 auto;
}

.comment-item {
  margin-bottom: 16px;
  padding-left: 20px;
  border-left: 2px solid #eee;
}

.comment-content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.comment-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.comment-author {
  font-weight: bold;
  font-size: 14px;
}

.comment-text {
  font-size: 16px;
  color: #333;
}

.reply-input {
  margin-top: 10px;
  display: flex;
  gap: 10px;
}

.child-comments {
  margin-left: 20px;
  margin-top: 10px;
}

.value-html {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  height: 100px;
}
</style>